<template>
  <div class="el-form-item">
    <div class="el-form-item__content">
      <div class="el-input">
        <input
          type="text"
          readonly="readonly"
          autocomplete="off"
          :placeholder="title"
          class="el-input__inner"
          @click="handleClick"
          :value="targetDate"
        />
      </div>
    </div>
    <popup v-model="showDatePicker" position="bottom">
      <datetime-picker
        v-model="currentDate"
        @cancel="handlePopClose"
        @confirm="handlePopConfirm"
        type="date"
        :title="title"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </popup>
  </div>
</template>
<script>
import { DatetimePicker, Popup, Cell } from "vant";

export default {
  props: {
    title: {
      type: String,
      default: "选择年月日",
    },
    targetDate: {
      type: String,
      default: "",
    },
  },
  //组件注入
  components: { DatetimePicker, Popup, Cell },
  //存放数据
  data() {
    return {
      showDatePicker: false,
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(),
      currentDate: this.targetDate || new Date(),
    };
  },
  methods: {
    getNum(i) {
      return i < 10 ? "0" + i : i;
    },
    getFormatDate(timeStamp) {
      if (!timeStamp) {
        return "";
      }
      const date = new Date(timeStamp); // 获取时间
      const year = date.getFullYear(); // 获取年
      const month = date.getMonth() + 1; // 获取月
      const strDate = date.getDate(); // 获取日
      return `${year}-${this.getNum(month)}-${this.getNum(strDate)}`;
    },
    handleClick(evt) {
      this.showDatePicker = true;
    },
    handlePopClose(evt) {
      this.showDatePicker = false;
    },
    handlePopConfirm(val) {
      this.$emit("changeDate", this.getFormatDate(val));
      this.handlePopClose();
    },
  },
};
</script>
<style></style>
